package ru.xeden.web.request.internal;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;

import javax.servlet.http.HttpServletResponse;

import ru.xeden.core.common.Utils;
import ru.xeden.web.request.IResponse;

public class ResponseImpl implements IResponse
{
    private static final String DEFAULT_ENCODING = "UTF-8";
    private final HttpServletResponse response;
    private String encoding = DEFAULT_ENCODING;

    public ResponseImpl(HttpServletResponse response, String encoding)
    {
        assert response != null;
        this.response = response;
    }

    public PrintWriter getPrintWriter(String contentType) throws IOException
    {
        assert !Utils.isEmpty(contentType);
        OutputStream os = getOutputStream(contentType);
        Writer w = new OutputStreamWriter(os, response.getCharacterEncoding() );

        return new PrintWriter(new BufferedWriter(w));
    }

    public String encodeURL(String URL)
    {
        return response.encodeURL(URL);
    }

    public String encodeRedirectURL(String URL)
    {
        return response.encodeRedirectURL(URL);
    }

    public void sendRedirect(String URL) throws IOException
    {
        response.sendRedirect(URL);
    }

    public void setStatus(int sc)
    {
        response.setStatus(sc);
    }

    public OutputStream getOutputStream(String contentType) throws IOException
    {
        assert !Utils.isEmpty(contentType);
        response.setContentType(contentType);
        response.setCharacterEncoding(encoding);
        return response.getOutputStream();
    }

    public void sendError(int sc, String message) throws IOException
    {
        response.sendError(sc, message);
    }

    public void setContentLength(int length)
    {
        response.setContentLength(length);
    }

    public void setDateHeader(String name, long date)
    {
        response.setDateHeader(name, date);
    }

    public void setHeader(String name, String value)
    {
        response.setHeader(name, value);
    }

    public void setIntHeader(String name, int value)
    {
        response.setIntHeader(name, value);
    }

    public boolean isCommitted()
    {
        return response.isCommitted();
    }

    public void disableCompression()
    {
        //FIXME
//        request.setAttribute(InternalConstants.SUPPRESS_COMPRESSION, true);
    }
}
